home *** CD-ROM | disk | FTP | other *** search
- Path: rain.fr!world-net!usenet
- From: Frederic LACHASSE <lachass@worldnet.fr>
- Newsgroups: comp.lang.c++
- Subject: Re: Comparing Struct elements
- Date: Fri, 02 Feb 1996 22:14:34 +0000
- Organization: World-Net information exchange, Internet provider.
- Message-ID: <VA.00000018.00c6ba71@fred>
- References: <4eo1va$s6k@camelot.ccs.neu.edu>
- Reply-To: lachass@worldnet.fr
- NNTP-Posting-Host: client87.sct.fr
- X-Newsreader: Virtual Access by Ashmount Research Ltd, http://www.ashmount.com
-
- bhardwaj@ccs.neu.edu (saurabh bhardwaj) wrote:
- << I've been trying to compare structure elements using the if Statement. Here
- is the code:
-
-
- double NumericVal(ClassRec& LetGrade){
-
- cout << "assgning struct member usin . " << LetGrade.
- Grade << '\n';
- if(LetGrade.Grade == "A") return(4.000);
- else if(LetGrade.Grade == "A-") return(3.666);
- else if(LetGrade.Grade == "B+") return(3.333);
- else return 0;
- }
-
- where LetGrade is the following struct:
-
- struct ClassRec {
- char Grade[3];
- int QH;
- char Name[10];
- };
-
- I can't seem to compare the elements of the Grade[3] with "A" or "A-" or "B+"
- The function invariable returns 0. I've also tried using the -> operator. It
- doesn't work either!!! Anyone know why??? I'll appreciate any help. >>
-
- Your error is that operator == does not compare strings, it compares pointers
- to char, so LetGrade.Grade evaluates to the pointer to the first character of
- the LetGrade.Grade array and "A" evaluates to a pointer in static memory where
- the compiler has stored the constant string. Obviously, the two have different
- addresses, so the pointers are different.
-
- To compare strings, you need to call a library functions. The standard one is
- defined in string.h:
-
- int strcmp(const char *, const char *);
-
- and returns -1 if the first string is before (alphabetical order) the second, 0
- if they are identical and +1 otherwise.
-
- Your test should be written:
-
- if(strcmp(LetGrade.Grade, "A") == 0) return(4.000);
- else if(strcmp(LetGrade.Grade, "A-") == 0) return(3.666);
- else if(strcmp(LetGrade.Grade, "B+") == 0) return(3.333);
- else return 0;
-
- I hope this'll help.
-
- Frederic LACHASSE (ECP 86)
- CompuServe: 100530,2005
- Internet: lachass@worldnet.fr
-
-